package me.xlgp.xiquzimu.ui.changci;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;

import org.jetbrains.annotations.NotNull;

import me.xlgp.xiquzimu.R;
import me.xlgp.xiquzimu.adapter.BaseAdapter;
import me.xlgp.xiquzimu.databinding.ChangCiItemEditBinding;
import me.xlgp.xiquzimu.model.ChangCi;

public class ChangCiEditAdapter extends BaseAdapter<ChangCi> {

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {

        ChangCiItemEditBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.chang_ci_item_edit, parent, false);

        return new ViewHolder(binding);
    }

    public int addItem() {
        int position = getItemCount();
        notifyItemInserted(position);
        notifyItemChanged(position);
        return position - 1;
    }


    public void removeItem(int position) {
        notifyItemRemoved(position);
        list.remove(position);
        //受影响的item都刷新position
        notifyItemRangeChanged(position, list.size() - 1);
    }

    static class ViewHolder extends BaseAdapter.ViewHolder<ChangCi> {

        private ChangCiItemEditBinding binding;

        public ViewHolder(ChangCiItemEditBinding binding) {
            this(binding.getRoot());
            this.binding = binding;
            binding.remove.setOnClickListener(this::createAlertDialog);
        }

        public ViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
        }

        private void createAlertDialog(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
            builder.setTitle("删除")
                    .setMessage("请选择操作")
                    .setPositiveButton("删除该项", (dialog, which) -> onItemClickListener.onItemClick(itemView, v, data, getAdapterPosition()))
                    .setNegativeButton("取消", (dialog, which) -> {
                    }).show();
        }

        @Override
        public void setData(ChangCi data) {
            super.setData(data);
            binding.setChangci(data);
            binding.executePendingBindings();
        }
    }
}
